package com.imooc.controller;

import com.imooc.domain.Girl;
import com.imooc.domain.Result;
import com.imooc.respository.GirlsRespository;
import com.imooc.service.GirlsService;
import com.imooc.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by ancy on 2017/7/8.
 */
@RestController
public class GirlController {

    @Autowired
    private GirlsRespository girlsRespository;

    @Autowired
    private GirlsService girlsService;

    /**
     *   查询所有的女生list
     * @return
     */
    @GetMapping (value = "/girls")
    public List <Girl>  girlList() {
        return  girlsRespository.findAll(); //
    }

    @PostMapping(value = "/girls")
    public  Result<Girl>  grilsAdd(@Valid Girl girl , BindingResult bindingResult) {// 属性校验

        if (bindingResult.hasErrors()) {
            return ResultUtil.error(500,bindingResult.getFieldError().getDefaultMessage());
        }

        Girl girl01 = new Girl();
        girl01.setName(girl.getName());
        girl01.setAge(girl.getAge());
        Girl girl1 = girlsRespository.save(girl01);
        return  ResultUtil.success(girl1);
    }

    @GetMapping(value = "/girls/{id}")
    public Girl getGirlOne (@PathVariable("id") Integer id) {
        return  girlsRespository.findOne(id);
    }

    /**
     * 更新
     */
    @PostMapping(value = "/girls/{id}")
    public Girl  updateGirls (@PathVariable("id") Integer id,
                              @RequestParam(value = "name") String name,
                              @RequestParam (value = "age") Integer age) {
        Girl girl = new Girl();
        girl.setId(id);
        girl.setName(name);
        girl.setAge(age);

        Girl girl1 = girlsRespository.save(girl);
        return girl1;
    }

    /**
     * 删除
     */
    @DeleteMapping(value = "girls/{id}")
    public  void delGirl (@PathVariable("id") Integer id) {
        girlsRespository.delete(id);
    }

    @GetMapping(value = "/girls/age/{age}")
   public  List<Girl> girlListByAge(@PathVariable("age") Integer age){
        return  girlsRespository.findByAge(age);
   }

   @PostMapping(value = "/girls/two")
    public  void girlsTwo() {
       girlsService.insertTwo();
   }

   @GetMapping(value = "/girls/getAge/{id}")
   public  void  getAge (@PathVariable("id") Integer id) throws  Exception{
        girlsService.getAge(id);
   }

    @GetMapping(value = "/girlsbyname/{name}")
    public  Girl  getGirlByName (@PathVariable("name") String name) throws  Exception{
        return  girlsService.queryGirlByName(name);
    }

}
